package com.hj.user.service;

import com.hj.user.dao.UserInfoDaoImpl;
import com.hj.user.domain.UserInfo;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class UserInfoManagerImpl implements UserInfoManager{
    private static final Scanner INPUT = new Scanner(System.in);
    ArrayList<UserInfo> list = UserInfoDaoImpl.list;
    public static UserInfoDaoImpl userInfoDao=new UserInfoDaoImpl();
    @Override
    public void mainMenu() {
        userInfoDao.mainMenu();
    }

    @Override
    public void searchAll() {
        if(list.size() == 0){
            System.out.println("请先添加会员再查询！");
            System.out.println();
            return;
        }
        userInfoDao.searchAll();
        System.out.println();
    }

    @Override
    public void deleteUserInfo() {
        System.out.println("请输入要删除的会员的编号：");
        int id=INPUT.nextInt();
        int index=findById(id);
        if (index==-1){
            System.err.println("您要删除的会员不存在！");
            System.out.println();
            return;
        }
        System.out.println("您确定要删除吗？（y/n）");
        String choice=INPUT.next();
        if ("y".equals(choice)){
            userInfoDao.deleteUserInfo(index);
            System.out.println("删除成功！");
        }
        System.out.println();
    }

    @Override
    public void addUserInfo() {
        System.out.println("请输入新会员的姓名：");
        String name=INPUT.next();
        System.out.println("请输入新会员的入会日期：（yyy-MM-dd）");
        String date=INPUT.next();
        int newId;
        out:
        while (true) {
            int a=new Random().nextInt(9000)+1000;
            for (UserInfo userInfo : list) {
                if (a == userInfo.getId()) {
                    continue out;
                }
            }
            newId=a;
            break;
        }
        UserInfo userInfo=new UserInfo(newId,name,date);
        System.out.println("您确定要删除吗？（y/n）");
        String choice=INPUT.next();
        if ("y".equals(choice)){
            userInfoDao.addUserInfo(userInfo);
            System.out.println("添加成功！");
        }
        System.out.println();
    }

    @Override
    public int findById(int id) {
        int index=-1;
        for (int i = 0; i < list.size(); i++) {
            UserInfo user = list.get(i);
            if (user.getId()==id){
                index=i;
                break;
            }
        }
        return index;
    }
}